#!/usr/bin/python
# -*- coding: utf-8 -*-

#
# doppel/invocations.py
# Author:   François Labelle
# Added:    2011-09-07
#

#
# Copyright 2011 François Labelle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from doppel.stubactions import then_return_, then_raise_, then_call_, then_verify_exists_, then_forward_

class Invocation(object):
    _function_name = None
    _function_args = None
    _function_kwargs = None
    _actions = None


    def __init__(self, function_name, *function_args, **function_kwargs):
        #TODO Link to a mock.
        assert(isinstance(function_name, basestring))
        object.__init__(self)

        self._function_name = function_name
        self._function_args = function_args
        self._function_kwargs = function_kwargs
        self._actions = []


    @property
    def function_name_(self):
        return self._function_name


    @property
    def function_args_(self):
        return self._function_args


    @property
    def function_kwargs_(self):
        return self._function_kwargs


    def then_return_(self, returned_value):
        self._actions.append(then_return_(returned_value))
        return self


    def then_raise_(self, raised_exception):
        self._actions.append(then_raise_(raised_exception))
        return self


    def then_call_(self, called_function, *function_args, **function_kwargs):
        self._actions.append(then_call_(called_function, *function_args, **function_kwargs))
        return self


    def then_verify_exists_(self):
        self._actions.append(then_verify_exists_())
        return self


    def then_forward_(self):
        self._actions.append(then_forward_())
        return self


    def __str__(self):
        function_arguments_representation = repr(self._function_args)[1:-1]     # Removing the parentheses.

        # Keyword arguments are sorted by key so that the format of the generated string representation can be
        # consistently predicted, and thus asserted, without crazy gymnastics.
        for key in sorted(self._function_kwargs.iterkeys()):
            value = self._function_kwargs[key]
            function_arguments_representation += u', {0}={1}'.format(key, repr(value))

        return u"{0}({1})".format(self._function_name, function_arguments_representation)


